package com.csc531.edit;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

import com.csc531.R;
import com.csc531.managers.FriendManager;

public class FriendsEdit extends Activity {
	public static final String EMPTY_STRING = "";

	private AutoCompleteTextView _friendPeopleText;
	private EditText _friendPhoneText;
	private EditText _friendEmailText;
	private FriendManager friendManager;

	static ArrayList<String> _people;
	static final int SAVE = Menu.FIRST;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, SAVE, 0, R.string.task_edit_menu_item1);

		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)	{
		switch(item.getItemId()) {
		case SAVE:
			exitActivity();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(_friendPeopleText.getWindowToken(), 0);

		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_edit);

		friendManager = new FriendManager(getContentResolver());
		populatePeopleArrayList();

		ArrayAdapter<String> peopleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, _people);
		_friendPeopleText = (AutoCompleteTextView) findViewById(R.id.friend_suggest);
		_friendPeopleText.setAdapter(peopleAdapter);
		_friendPhoneText = (EditText) findViewById(R.id.friend_number);
		_friendEmailText = (EditText) findViewById(R.id.friend_email);

		populateFields();
	}

	private void exitActivity()	{
		setResult(RESULT_OK);
		saveState();
		finish();
	}

	private void populatePeopleArrayList() {
		_people = new ArrayList<String>();

		Uri contacts = ContactsContract.Contacts.CONTENT_URI;
		Cursor cursor = getContentResolver().query(contacts, null, null, null, null);

		while(cursor.moveToNext())
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
			String contact = cursor.getString(nameFieldColumnIndex);
			_people.add(contact);
		}

		cursor.close();
	}

	private void populatePhoneField() {
		String name = _friendPeopleText.getText().toString();
		String phoneId = null;
		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		startManagingCursor(cursor);

		while(cursor.moveToNext())
		{
			long contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))); 
			String contact = friendManager.getDisplayName(contactId);
			if(contact != null && contact.compareTo(name) == 0) {
				phoneId = friendManager.getContactsPhoneNumber(contactId);
				_friendPhoneText.setText(phoneId);
				break;
			}
		}

		cursor.close();
	}

	private void populateEmailField() {
		String name = _friendPeopleText.getText().toString();
		String email = new String();
		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

		while(cursor.moveToNext())
		{
			long contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))); 
			String contact = friendManager.getDisplayName(contactId);
			if(contact != null && contact.compareTo(name) == 0) {
				email = friendManager.getEmail(contactId);
				_friendEmailText.setText(email);
				break;
			}
		}

		cursor.close();
	}

	private void populateFields() {
		_friendPeopleText.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_DEL) {
					_friendPhoneText.setText(EMPTY_STRING);
					_friendPhoneText.setEnabled(true);

					_friendEmailText.setText(EMPTY_STRING);
					_friendEmailText.setEnabled(true);
				}

				return false;
			}
		});


		_friendPhoneText.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				populatePhoneField();

				if(friendManager.contactExistsByName(_friendPeopleText.getText().toString())) {
					_friendPhoneText.setEnabled(false);	
				}

				return false;
			}
		});

		_friendEmailText.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				populateEmailField();

				if(friendManager.contactExistsByName(_friendPeopleText.getText().toString())) {
					_friendEmailText.setEnabled(false);
				}

				return false;
			}

		});
	}

	private void saveState() {
		String name = _friendPeopleText.getText().toString();
		String email = _friendEmailText.getText().toString();
		String phone = _friendPhoneText.getText().toString();

		if(name.length() == 0 || phone.length() == 0 ) {	
			Toast.makeText(FriendsEdit.this, R.string.failure_adding_new_friend, Toast.LENGTH_SHORT).show();
			return;
		}

		if (friendManager.contactExistsByName(name) == false)  {
			addNewContactToPhone(name,phone,email);
		} else {
			makeExistentContactAFriend(name);
		}
	}

	private void addNewContactToPhone(String name, String phone, String email) {
		friendManager.addNewContact(this, name, email, phone);
	}

	private void makeExistentContactAFriend(String name) {
		friendManager.makeExistentContactFriend(this, name);
	}
}
